import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/bean/Topic.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/database/db_praise.dart';
import 'package:flutter_chip/utils/date_utils.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/view/home/mcu_web.dart';
import 'package:flutter_chip/widget/RouteSlide.dart';
import 'package:flutter_chip/widget/view_image.dart';
import 'package:flutter_chip/widget/widget_comm.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

///发布的帖子

class MyTopicPage extends StatefulWidget {
  final userId;
  final bool isSelf;

  const MyTopicPage({Key key, this.userId, this.isSelf = false})
      : super(key: key);

  @override
  _MyTopicPageState createState() => _MyTopicPageState();
}

class _MyTopicPageState extends State<MyTopicPage> {
  EasyRefreshController controller = EasyRefreshController();
  var _item = [];
  int childCount = 0;

//数据库
  PraiseDao _praiseDao = PraiseDao();

  //所有点赞列表
  Set<String> _praiseSets;

  @override
  void initState() {
    super.initState();
    _getDatas();
  }

  @override
  Widget build(BuildContext context) {
    return EasyRefresh.custom(
      enableControlFinishRefresh: true,
      header: CommWidget.commHeader(),
      emptyWidget: childCount == 0 ? CommWidget.nullWidget() : null,
      controller: controller,
      slivers: <Widget>[
        SliverList(
            delegate: SliverChildBuilderDelegate((context, index) {
          return _itemBuilder(context, index);
        }, childCount: childCount))
      ],
      onRefresh: () => _getDatas(),
    );
  }

  ///列表Item
  Widget _itemBuilder(BuildContext context, int index) {
    Topic topic = _item[index];
    String date = topic.createAt.split(" ")[0];
    String year = date.split("-")[0];
    String month = date.split("-")[1];
    String day = date.split("-")[2];
    bool thisYear = DateTime.now().year == int.parse(year);

    //左边日期组件
    Widget _dateWidget = Container(
        alignment: Alignment.topLeft,
        margin: EdgeInsets.only(left: 10),
        child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                day,
                style: TextStyle(
                    color: Colors.black,
                    fontSize: 18,
                    fontWeight: FontWeight.bold),
              ),
              Text(
                "${DateUtil.month2Ch(month)}月",
                style: TextStyle(fontSize: 12),
              ),
            ]),
        width: 60);
    return Container(
        padding: EdgeInsets.only(top: 10),
        color: Colors.white,
        alignment: Alignment.topLeft,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Offstage(
              offstage: thisYear,
              child: Container(
                margin: EdgeInsets.only(bottom: 10),
                child: Text("$year年", style: TextStyle(fontSize: 12)),
              ),
            ),
            Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  _dateWidget,
                  Expanded(
                    child: _contentWidget(topic),
                    flex: 1,
                  ),
                ]),
            SizedBox(height: 10),
            _bottomWidget(topic),
            SizedBox(height: 10),
            Offstage(
              child: Container(height: 10, color: Color(0xffF2F2F2)),
              offstage: index == _item.length - 1,
            ),
          ],
        ));
  }

  ///内容区域
  Widget _contentWidget(Topic topic) {
    bool showTitle = null == topic.title || topic.title.isEmpty;
    bool showPic = null != topic.imageUrls && topic.imageUrls.isNotEmpty;
    Widget picWidget;
    if (showPic) {
      List<String> images = topic.imageUrls.split(",");
      List<Widget> childs = images.map((item) {
        BorderRadius borderRadius;
        if (images.length == 1) {
          borderRadius = BorderRadius.circular(4);
        } else if (item == images.first) {
          borderRadius = BorderRadius.only(
              topLeft: Radius.circular(4),
              topRight: Radius.circular(0),
              bottomLeft: Radius.circular(4),
              bottomRight: Radius.circular(0));
        } else if (item == images.last) {
          borderRadius = BorderRadius.only(
              topLeft: Radius.circular(0),
              topRight: Radius.circular(4),
              bottomLeft: Radius.circular(0),
              bottomRight: Radius.circular(4));
        } else {
          borderRadius = BorderRadius.circular(0);
        }
        double picWidth =
            (MediaQuery.of(context).size.width - 80) / images.length - 4;
        if (images.length == 1) {
          picWidth = (MediaQuery.of(context).size.width - 80) / images.length;
        }
        return GestureDetector(
            child: Container(
              width: picWidth,
              height: picWidth * 3 / 4,
              child: ClipRRect(
                borderRadius: borderRadius,
                child: CachedNetworkImage(
                  imageUrl: Api.getUrl(item),
                  fit: BoxFit.cover,
                  errorWidget: (context, url, error) => CommWidget.imgError(),
                ),
              ),
            ),
            onTap: () {
              int current = images.indexOf(item);
              Navigator.of(context).push(
                RouteSlide(
                  ImagePage(images, current: current),
                ),
              );
            });
      }).toList();
      picWidget = Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween, children: childs);
    }
    return Container(
      margin: EdgeInsets.only(right: 10),
      child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Row(
              children: <Widget>[
                Expanded(
                  child: Text(
                    null == topic.typeDesc ? "" : topic.typeDesc,
                    style: TextStyle(color: Color(0xff999999), fontSize: 12),
                  ),
                  flex: 1,
                ),
                Offstage(
                  offstage: !widget.isSelf,
                  child: GestureDetector(
                    child: Text(
                      "删除",
                      style: TextStyle(color: Colors.grey, fontSize: 12),
                    ),
                    onTap: () => showMsgDialog(context, topic.topicId),
                  ),
                ),
              ],
            ),
            SizedBox(height: 10),
            Offstage(
                offstage: showTitle,
                child: Container(
                  child: Text(!showTitle ? topic.title : '没有内容',
                      style: TextStyle(fontWeight: FontWeight.bold)),
                )),
            Offstage(offstage: showTitle, child: SizedBox(height: 6)),
            Container(
              child: Text(topic.content),
            ),
            Offstage(offstage: !showPic, child: SizedBox(height: 6)),
            Offstage(offstage: !showPic, child: picWidget)
          ]),
    );
  }

  ///底部按钮
  Widget _bottomWidget(Topic topic) {
    bool isPraise = null != _praiseSets && _praiseSets.contains(topic.topicId);
    Color colorPraise = isPraise ? Colors.redAccent : Color(0xff999999);
    TextStyle stylePraise = TextStyle(color: colorPraise);

    return Row(mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[
      SizedBox(width: 60),
      GestureDetector(
          child: Row(children: <Widget>[
            Icon(Icons.share, size: 18, color: Color(0xff999999)),
            SizedBox(width: 4),
            Text('分享', style: TextStyle(color: Color(0xff999999)))
          ]),
          onTap: () {}),
      SizedBox(width: 40),
      GestureDetector(
          child: Row(children: <Widget>[
            Icon(Icons.speaker_notes, size: 18, color: Color(0xff999999)),
            SizedBox(width: 4),
            Text(
              '${topic.repayCount}',
              style: TextStyle(
                color: Color(0xff999999),
              ),
            )
          ]),
          onTap: () {
            if (topic.content.startsWith("![")) {
              Navigator.of(context).push(
                MaterialPageRoute(builder: (_) {
                  return WebInfoPage(topic.title, topic.content.substring(2),
                      type: "web");
                }),
              );
              return;
            }
            String url = "${Routers.PAGE_FORUMINFO}?topicId=${topic.topicId}";
            Routers.router.navigateTo(context, url,
                transition: TransitionType.inFromRight);
          }),
      Expanded(
        child: Container(),
        flex: 1,
      ),
      GestureDetector(
          child: Row(children: <Widget>[
            Icon(Icons.thumb_up, size: 18, color: colorPraise),
            SizedBox(width: 4),
            Text('${topic.praiseCount}', style: stylePraise)
          ]),
          onTap: () async {
            if (!isPraise) {
              _praiseDao.insert(topic.topicId);
              _praiseSets = await _praiseDao.queryAll();
              _update(topic.topicId, 1);
              setState(() {
                topic.isPraise = true;
                topic.praiseCount++;
              });
            } else {
              _praiseDao.delPraise(topic.topicId);
              _praiseSets = await _praiseDao.queryAll();
              _update(topic.topicId, -1);
              setState(() {
                topic.isPraise = false;
                if (topic.praiseCount > 0) {
                  topic.praiseCount--;
                }
              });
            }
          }),
      SizedBox(width: 10),
    ]);
  }

  ///信息提示对话框
  void showMsgDialog(BuildContext context, String topicId) {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("提示"),
            content: Text(
              "该帖所关联的所有评论也将同步删除，您确定要继续操作吗？",
              style: TextStyle(fontSize: 16),
            ),
            actions: <Widget>[
              FlatButton(
                child: Text("取消"),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
              FlatButton(
                child: Text("确定"),
                onPressed: () {
                  Navigator.pop(context);
                  _delTopic(topicId);
                },
              ),
            ],
          );
        });
  }

  void _update(String topicId, int praise) {
    Map<String, String> params = Map();
    params["topicId"] = topicId;
    params["praiseCount"] = "$praise";
    Http.post(Api.URL_TOPIC_UPDATE, params: params);
  }

  ///刪除话题
  Future _delTopic(String topicId) async {
    String url = "${Api.URL_TOPIC_DEL}?topicId=$topicId";
    Http.get(url, successCallBack: (data) {
      Toast.show("操作成功");
      _getDatas();
    }, errorCallBack: (error) {
      Toast.show(error);
    });
  }

  ///获取数据
  Future _getDatas() async {
    Map<String, String> params = Map();
    params["pageSize"] = "100";
    params["pageNum"] = "0";
    params["userId"] = widget.userId;
    Http.get(Api.URL_TOPIC_LIST, params: params, successCallBack: (data) {
      controller.finishRefresh();
      List list = json.decode(data).map((m) => Topic.fromJson(m)).toList();
      setState(() {
        _item.clear();
        _item.addAll(list);
        childCount = _item.length;
      });
    }, errorCallBack: (msg) {
      controller.finishRefresh();
    });
  }
}
